<template>
  <div class="users-container">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
    </div>
    
    <div class="search-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索用户名或姓名"
        class="search-input"
        clearable
      />
      <el-select v-model="roleFilter" placeholder="角色" clearable>
        <el-option label="管理员" value="admin" />
        <el-option label="收银员" value="staff" />
      </el-select>
      <el-select v-model="departmentFilter" placeholder="部门" clearable>
        <el-option 
          v-for="dept in departments" 
          :key="dept.id" 
          :label="dept.name" 
          :value="dept.id" 
        />
      </el-select>
      <el-select v-model="statusFilter" placeholder="状态" clearable>
        <el-option label="启用" :value="true" />
        <el-option label="禁用" :value="false" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    
    <el-table
      :data="filteredUsers"
      style="width: 100%"
      border
      stripe
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" class-name="text-left" />
      <el-table-column prop="name" label="姓名" class-name="text-left" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="department" label="部门">
        <template #default="scope">
          <el-tag v-if="scope.row.department" type="success">
            {{ scope.row.department.name }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色">
        <template #default="scope">
          <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
            {{ scope.row.role === 'admin' ? '管理员' : '收银员' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'info'">
            {{ scope.row.status ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="info"
            size="small"
            plain
            @click="handleResetPassword(scope.row)"
          >
            重置密码
          </el-button>
          <el-button
            :type="scope.row.status ? 'warning' : 'success'"
            size="small"
            plain
            @click="handleToggleStatus(scope.row)"
            :disabled="scope.row.id === currentUserId"
          >
            {{ scope.row.status ? '禁用' : '启用' }}
          </el-button>
          <el-button
            type="danger"
            size="small"
            plain
            @click="handleDelete(scope.row)"
            :disabled="scope.row.id === currentUserId"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '新增用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="不修改请留空" :required="!isEdit" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <el-select v-model="userForm.departmentId" placeholder="请选择部门" clearable>
            <el-option 
              v-for="dept in departments" 
              :key="dept.id" 
              :label="dept.name" 
              :value="dept.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色">
            <el-option :label="'管理员'" :value="1" />
            <el-option :label="'收银员'" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="isEdit">
          <el-switch v-model="userForm.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPwdDialogVisible"
      title="重置用户密码"
      width="500px"
    >
      <el-form
        ref="resetPwdFormRef"
        :model="resetPwdForm"
        :rules="resetPwdRules"
        label-width="100px"
      >
        <el-form-item label="用户">
          <span>{{ resetPwdForm.username }}</span>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input 
            v-model="resetPwdForm.password" 
            type="password" 
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="resetPwdForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPwdDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitResetPassword" :loading="resetPwdLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'

// 用户列表
const users = ref([])
const loading = ref(false)

// 部门列表
const departments = ref([])

// 当前登录用户ID
const currentUserId = ref(null)

// 搜索和筛选条件
const searchText = ref('')
const roleFilter = ref('')
const departmentFilter = ref('')
const statusFilter = ref('')

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const userFormRef = ref(null)

// 重置密码对话框相关
const resetPwdDialogVisible = ref(false)
const resetPwdLoading = ref(false)
const resetPwdFormRef = ref(null)
const resetPwdForm = reactive({
  id: null,
  username: '',
  password: '',
  confirmPassword: ''
})

// 用户表单
const userForm = reactive({
  id: null,
  username: '',
  password: '',
  name: '',
  phone: '',
  roleId: 2, // 默认为收银员
  departmentId: null,
  status: true
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: (form) => !isEdit.value, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 重置密码表单验证规则
const resetPwdRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== resetPwdForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 过滤后的用户列表
const filteredUsers = computed(() => {
  let result = users.value
  
  // 按用户名或姓名搜索
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase()
    result = result.filter(user => {
      return user.username.toLowerCase().includes(keyword) || 
             (user.name && user.name.toLowerCase().includes(keyword))
    })
  }
  
  // 按角色筛选
  if (roleFilter.value) {
    result = result.filter(user => user.role === roleFilter.value)
  }
  
  // 按部门筛选
  if (departmentFilter.value) {
    result = result.filter(user => user.department && user.department.id === departmentFilter.value)
  }
  
  // 按状态筛选
  if (statusFilter.value !== '') {
    result = result.filter(user => user.status === statusFilter.value)
  }
  
  return result
})

// 获取当前登录用户信息
const getCurrentUser = () => {
  const userStr = localStorage.getItem('user')
  if (userStr) {
    try {
      const user = JSON.parse(userStr)
      currentUserId.value = user.id
    } catch (e) {
      console.error('解析用户信息失败', e)
    }
  }
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await api.get('/users')
    if (response.data && response.data.status === 'success') {
      users.value = response.data.data
    } else {
      ElMessage.error('获取用户列表失败: ' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const response = await api.get('/departments')
    if (response.data && response.data.status === 'success') {
      departments.value = response.data.data
    } else {
      ElMessage.error('获取部门列表失败: ' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

// 搜索
const handleSearch = () => {
  // 直接使用计算属性过滤，无需额外操作
}

// 重置搜索条件
const resetSearch = () => {
  searchText.value = ''
  roleFilter.value = ''
  departmentFilter.value = ''
  statusFilter.value = ''
}

// 新增用户
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  isEdit.value = true
  // 复制用户数据，但不包含密码
  userForm.id = row.id
  userForm.username = row.username
  userForm.password = '' // 不显示密码
  userForm.name = row.name || ''
  userForm.phone = row.phone || ''
  userForm.status = row.status
  userForm.departmentId = row.department ? row.department.id : null
  
  // 根据角色名称设置角色ID
  if (row.role === 'admin') {
    userForm.roleId = 1
  } else {
    userForm.roleId = 2
  }
  
  dialogVisible.value = true
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  try {
    // 禁止修改自己的状态
    if (row.id === currentUserId.value) {
      ElMessage.warning('不能修改当前登录用户的状态')
      return
    }
    
    const newStatus = !row.status
    const response = await api.put(`/users/${row.id}`, {
      status: newStatus
    })
    
    if (response.data && response.data.status === 'success') {
      row.status = newStatus
      ElMessage.success(`用户已${newStatus ? '启用' : '禁用'}`)
    } else {
      ElMessage.error('更新状态失败: ' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('更新用户状态失败:', error)
    ElMessage.error('更新用户状态失败')
  }
}

// 删除用户
const handleDelete = (row) => {
  // 禁止删除自己
  if (row.id === currentUserId.value) {
    ElMessage.warning('不能删除当前登录用户')
    return
  }
  
  // 构建删除风险提示信息
  const warningMessage = `
    <div class="delete-warning">
      <p><strong>确定要删除用户 "${row.username}" 吗？</strong></p>
      <p class="warning-title">删除后将导致以下后果：</p>
      <ul>
        <li>此操作将<span class="text-danger">永久删除</span>该用户账户，无法恢复</li>
        <li>该用户的所有登录凭证将立即失效</li>
        <li>该用户创建的历史订单记录将保留，但无法关联到具体操作人员</li>
        <li>该用户的系统使用权限将被撤销</li>
      </ul>
      <p class="warning-note">建议在删除前确认该用户已不再需要使用系统</p>
    </div>
  `;
  
  ElMessageBox.confirm(
    warningMessage,
    '删除用户风险警告',
    {
      confirmButtonText: '确认删除',
    cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
      confirmButtonClass: 'el-button--danger'
    }
  ).then(async () => {
    try {
      loading.value = true
      
      const response = await api.delete(`/users/${row.id}`)
      
      if (response.data && response.data.status === 'success') {
        ElMessage.success('删除成功')
        // 重新获取用户列表
        fetchUsers()
      } else {
        ElMessage.error('删除失败: ' + (response.data?.message || '未知错误'))
      }
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    ElMessage.info('已取消删除操作')
  })
}

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  
  Object.assign(userForm, {
    id: null,
    username: '',
    password: '',
    name: '',
    phone: '',
    roleId: 2, // 默认为收银员
    departmentId: null,
    status: true
  })
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return
  
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      
      try {
        // 准备提交的数据
        const userData = { ...userForm }
        
        // 如果是编辑模式且密码为空，则删除密码字段
        if (isEdit.value && !userData.password) {
          delete userData.password
        }
        
        let response
        
        if (isEdit.value) {
          // 编辑用户
          response = await api.put(`/users/${userData.id}`, userData)
        } else {
          // 新增用户
          response = await api.post('/users', userData)
        }
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success(isEdit.value ? '用户编辑成功' : '用户添加成功')
          dialogVisible.value = false
          // 重新获取用户列表
          fetchUsers()
        } else {
          ElMessage.error((isEdit.value ? '编辑' : '添加') + '用户失败: ' + (response.data?.message || '未知错误'))
        }
      } catch (error) {
        console.error(isEdit.value ? '编辑用户失败:' : '添加用户失败:', error)
        ElMessage.error(isEdit.value ? '编辑用户失败' : '添加用户失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置密码
const handleResetPassword = (row) => {
  resetPwdForm.id = row.id
  resetPwdForm.username = row.username
  resetPwdForm.password = ''
  resetPwdForm.confirmPassword = ''
  resetPwdDialogVisible.value = true
}

// 提交重置密码
const submitResetPassword = async () => {
  if (!resetPwdFormRef.value) return
  
  resetPwdFormRef.value.validate(async (valid) => {
    if (valid) {
      resetPwdLoading.value = true
      
      try {
        const response = await api.put(`/users/${resetPwdForm.id}/reset-password`, {
          password: resetPwdForm.password
        })
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success('密码重置成功')
          resetPwdDialogVisible.value = false
        } else {
          ElMessage.error('重置密码失败: ' + (response.data?.message || '未知错误'))
        }
      } catch (error) {
        console.error('重置密码失败:', error)
        ElMessage.error('重置密码失败')
      } finally {
        resetPwdLoading.value = false
      }
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  getCurrentUser()
  fetchUsers()
  fetchDepartments()
})
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  margin: 0;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.delete-warning {
  text-align: left;
  margin-top: 10px;
}

.warning-title {
  font-weight: bold;
  margin-top: 10px;
  color: #E6A23C;
}

.warning-note {
  font-style: italic;
  margin-top: 10px;
  color: #909399;
}

.text-danger {
  color: #F56C6C;
  font-weight: bold;
}
</style> 